package com.yuanheng100.ems4j.web;

import com.yuanheng100.ems4j.web.utils.ConfigFile;
import org.slf4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Jetty启动类
 */
public class WebLauncher
{
    private static final Logger log = LoggerFactory.getLogger(WebLauncher.class);

    private static final String PORTSTR = ConfigFile.getProperty("system.web.port");
    private static final String CONTEXT_PATH = ConfigFile.getProperty("system.web.context.path"); // 项目名称
    private static final String PROJECT_PATH = ClassLoader.getSystemClassLoader().getResource("").getPath();
    //private static final String GLOBAL_XML_PATH = PROJECT_PATH + File.separatorChar + "conf" + File.separatorChar + "web.xml";
    private static final String WEB_APP_PATH = PROJECT_PATH + File.separatorChar + "webapp";
    private static final String TEMP_PATH = PROJECT_PATH + File.separatorChar + "temp";

    private Server server = new Server(Integer.parseInt(PORTSTR));

    public void start()
    {
        log.info("Jetty 启动中...");

        WebAppContext context = new WebAppContext(WEB_APP_PATH, CONTEXT_PATH);
        context.setDescriptor(WEB_APP_PATH + "/WEB-INF/web.xml");
        // context.setResourceBase(WEB_APP_PATH);
        // context.setContextPath(CONTEXT_PATH);
        context.setTempDirectory(new File(TEMP_PATH));
        context.setParentLoaderPriority(true);
        context.setClassLoader(Thread.currentThread().getContextClassLoader());

        server.setHandler(context);
        try
        {
            server.start();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        log.info("Jetty启动完毕。请访问 http://localhost:"+PORTSTR+CONTEXT_PATH);
        /*
         * try
         * {
         * server.join();
         * } catch (InterruptedException e)
         * {
         * e.printStackTrace();
         * }
         */
    }

    public void stop() throws Exception
    {
        log.info("Jetty stopping...");
        server.stop();
        server.destroy();
        log.info("Jetty stoped");
    }
}
